package com.scuec.groupfive.mapper;

import com.scuec.groupfive.entity.SysLog;
import org.apache.ibatis.annotations.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Mapper
public interface SysLogMapper {

    @Insert("INSERT INTO sys_log(userID, Log_Content, IP_Address, OS, IE, CreateDate, Remark) " +
            "VALUES(#{userID}, #{logContent}, #{ipAddress}, #{os}, #{ie}, #{createDate}, #{remark})")
    @Options(useGeneratedKeys = true, keyProperty = "logID")
    int insertLog(SysLog log);

    @Select("SELECT * FROM sys_log ORDER BY CreateDate DESC")
    List<SysLog> selectAllLogs();

    @Select("<script>" +
            "SELECT l.*, u.username FROM sys_log l " +
            "LEFT JOIN users u ON l.userID = u.user_id " +  // 修改这里：u.userID → u.user_id
            "<where>" +
            "   <if test='username != null'> AND u.username LIKE CONCAT('%', #{username}, '%')</if>" +
            "   <if test='startDate != null'> AND l.CreateDate &gt;= #{startDate}</if>" +
            "   <if test='endDate != null'> AND l.CreateDate &lt;= #{endDate}</if>" +
            "</where>" +
            "ORDER BY l.CreateDate DESC " +
            "LIMIT #{offset}, #{pageSize}" +
            "</script>")
    List<SysLog> selectLogsByCondition(@Param("username") String username,
                                       @Param("startDate") Date startDate,
                                       @Param("endDate") Date endDate,
                                       @Param("offset") int offset,
                                       @Param("pageSize") int pageSize);

    @Select("<script>" +
            "SELECT COUNT(*) FROM sys_log l " +
            "LEFT JOIN users u ON l.userID = u.user_id " +  // 同样修改这里
            "<where>" +
            "   <if test='username != null'> AND u.username LIKE CONCAT('%', #{username}, '%')</if>" +
            "   <if test='startDate != null'> AND l.CreateDate &gt;= #{startDate}</if>" +
            "   <if test='endDate != null'> AND l.CreateDate &lt;= #{endDate}</if>" +
            "</where>" +
            "</script>")
    int countLogsByCondition(@Param("username") String username,
                             @Param("startDate") Date startDate,
                             @Param("endDate") Date endDate);

    // 新增统计用户登录次数方法
    @Select("<script>" +
            "SELECT l.userID, u.username, COUNT(*) AS loginCount " +
            "FROM sys_log l " +
            "LEFT JOIN users u ON l.userID = u.user_id " +
            "WHERE l.Log_Content = '用户登录' " +
            "<if test='startDate != null'> AND l.CreateDate &gt;= #{startDate}</if>" +
            "<if test='endDate != null'> AND l.CreateDate &lt;= #{endDate}</if>" +
            "GROUP BY l.userID, u.username" +
            "</script>")
    List<Map<String, Object>> countUserLogins(@Param("startDate") Date startDate,
                                              @Param("endDate") Date endDate);
}